//
//  AppDelegateJMessage.swift
//  MT
//
//  Created by ooops on 2019/12/16.
//  Copyright © 2019 张强. All rights reserved.
//

import UIKit
import Foundation
import JMessage
import MTCategory

extension AppDelegate {
    
    func setupJMessage(options: [AnyHashable : Any]?) {
        
        #if DEBUG
        JMessage.setupJMessage(options, appKey: JPushAppSecretKey, channel: nil, apsForProduction: false, category: nil, messageRoaming: true)
        #else
        JMessage.setupJMessage(options, appKey: JPushAppSecretKey, channel: nil, apsForProduction: true, category: nil, messageRoaming: true)
        #endif
        
        JMessage.add(self, with: nil)
        
        if #available(iOS 8, *) {
            JMessage.register(
                forRemoteNotificationTypes: UIUserNotificationType.badge.rawValue |
                    UIUserNotificationType.sound.rawValue |
                    UIUserNotificationType.alert.rawValue,
                categories: nil)
        } else {
            // iOS 8 以前 categories 必须为nil
            JMessage.register(
                forRemoteNotificationTypes: UIRemoteNotificationType.badge.rawValue |
                    UIRemoteNotificationType.sound.rawValue |
                    UIRemoteNotificationType.alert.rawValue,
                categories: nil)
        }
        
//        IMLoginManager.login(complete: {
//            
//        }) {
//            
//        }
    }
    
}

//JMSGEventDelegate、
// MARK: - 群组 / 俱乐部相关事件
extension AppDelegate: JMSGGroupDelegate {
    func onReceiveApplyJoinGroupApprovalEvent(_ event: JMSGApplyJoinGroupEvent!) {
        
        /// 主动请缨申请入群的
        if event.isInitiativeApply {
            let currentUser = JMSGUser.myInfo()
            let info = JCVerificationInfo.create(username: (event?.groupID)!, nickname: "", appkey: currentUser.appKey!, resaon: event.reason, state: JCVerificationType.receive.rawValue, initiator: event.sendApplyUser.username, type: .group, eventId: event.eventID, clubId: (event?.groupID)!)
            
            /// 插入加入俱乐部申请数据
            JCVerificationInfoDB.shareInstance.insertData(info)
            
            NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateVerification), object: nil)
        } else {
            let currentUser = JMSGUser.myInfo()
            let info = JCVerificationInfo.create(username: event.groupID, nickname: "", appkey: currentUser.appKey!, resaon: event.reason, state: JCVerificationType.receive.rawValue, initiator: event.sendApplyUser.username, type: .group, eventId: event.eventID, clubId: event.groupID, isInitiativeApply: true)
            
            /// 插入加入俱乐部申请数据
            JCVerificationInfoDB.shareInstance.insertData(info)
            
            NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateVerification), object: nil)
        }
    }
    
    /// 同意 / 拒绝申请入群通知
    func onReceive(_ event: JMSGGroupAdminApprovalEvent!) {
        /*
         /// 管理员是否同意申请，YES：同意，NO：拒绝
         @property(nonatomic, assign, readonly) BOOL isAgreeApply;
         /// 申请入群事件的事件 id
         @property(nonatomic, strong, readonly) NSString *applyEventID;
         /// 群 gid
         @property(nonatomic, strong, readonly) NSString *groupID;
         /// 操作的管理员
         @property(nonatomic, strong, readonly) JMSGUser *groupAdmin;
         /// 申请或被邀请加入群的用户，即：实际入群的用户
         @property(nonatomic, strong, readonly) NSArray JMSG_GENERIC(__kindof JMSGUser *)*users;
         */
        /// 通过了俱乐部申请
        if event.isAgreeApply {
            let currentUser = JMSGUser.myInfo()
            let info = JCVerificationInfo.create(username: event.groupID, nickname: "", appkey: currentUser.appKey!, resaon: "", state: JCVerificationType.accept.rawValue, initiator: currentUser.username, type: .group, eventId: event.applyEventID)
            
            JCVerificationInfoDB.shareInstance.updateData(info)
            NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateVerification), object: nil)
        }
    }
}

extension AppDelegate: JMessageDelegate {
    func onDBMigrateStart() {
        MBProgressHUD_JChat.showMessage(message: "数据库升级中", toView: nil)
    }
    
    func onDBMigrateFinishedWithError(_ error: Error!) {
        MBProgressHUD_JChat.hide(forView: nil, animated: true)
        MBProgressHUD_JChat.show(text: "数据库升级完成", view: nil)
    }
    func onReceive(_ event: JMSGUserLoginStatusChangeEvent!) {
        switch event.eventType.rawValue {
        case JMSGLoginStatusChangeEventType.eventNotificationLoginKicked.rawValue,
             JMSGLoginStatusChangeEventType.eventNotificationServerAlterPassword.rawValue,
             JMSGLoginStatusChangeEventType.eventNotificationUserLoginStatusUnexpected.rawValue:
            _logout()
        default:
            break
        }
    }
    func onReceive(_ event: JMSGFriendNotificationEvent!) {
        switch event.eventType.rawValue {
        case JMSGFriendEventType.eventNotificationReceiveFriendInvitation.rawValue,
             JMSGFriendEventType.eventNotificationAcceptedFriendInvitation.rawValue,
             JMSGFriendEventType.eventNotificationDeclinedFriendInvitation.rawValue:
            cacheInvitation(event: event)
        case JMSGFriendEventType.eventNotificationReceiveServerFriendUpdate.rawValue:
            NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateFriendList), object: nil)
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateConversation), object: nil, userInfo: nil)
        case JMSGFriendEventType.eventNotificationDeletedFriend.rawValue:
            NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateFriendList), object: nil)
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateConversation), object: nil, userInfo: nil)
            if let u = event.getFromUser() {
                NotificationCenter.default.post(name: GlobalNotificationName.didRevokeFriend.name, object: nil, userInfo: ["userName" : u.username])
            }
        default:
            break
        }
    }
    
    /// 穿透时间 - 用于更新礼物接收状态
    /*
     * 前提要求, 礼物发送者被认为处于在线状态
     * 参考 http://docs.jiguang.cn/jmessage/client/ios_sdk/event/#_48 事件穿透
     * 时间发送在 tapGiftMessage 函数中
     * 业务逻辑如下
     * 礼物接受者 - 点击接收礼物 - 发送穿透命令通知礼物发送者 - 礼物状态改变了
     *
     */
//    func onReceive(_ transparentEvent: JMSGMessageTransparentEvent!) {
//        //let s = ""
//        /// 更新本地保存送礼物状态信息
//        if let dataString = transparentEvent?.transparentText {
//            let jsonData:Data = dataString.data(using: .utf8)!
//
//            let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
//            if dict != nil, let d = dict as? [String : Any], let msgId = d["msgId"] as? String, let status: Int = d["status"] as? Int {
//                let giftInfo: MTGiftInfo = MTGiftInfo.create(msgId: msgId, status: MTGiftInfoStatus(rawValue: status)!)
//                MTGiftInfoDB.shareInstance.insertData(giftInfo)
//            }
//        }
//    }
    
    private func cacheInvitation(event: JMSGNotificationEvent) {
        let friendEvent =  event as! JMSGFriendNotificationEvent
        let user = friendEvent.getFromUser()
        let reason = friendEvent.getReason()
        //let info = JCVerificationInfo.create(username: user!.username, nickname: user?.nickname, appkey: user!.appKey!, resaon: reason, state: JCVerificationType.wait.rawValue, initiator: user!.username)
        let info = JCVerificationInfo.create(username: user!.username, nickname: user?.nickname, appkey: user!.appKey!, resaon: reason, state: JCVerificationType.wait.rawValue, initiator: "", type: .single, eventId: friendEvent.eventID!, giftCount: 0, province: "", city: "", area: "")
        switch event.eventType.rawValue {
        case JMSGFriendEventType.eventNotificationReceiveFriendInvitation.rawValue:
            info.state = JCVerificationType.receive.rawValue
            JCVerificationInfoDB.shareInstance.insertData(info)
        case JMSGFriendEventType.eventNotificationAcceptedFriendInvitation.rawValue:
            info.state = JCVerificationType.accept.rawValue
            JCVerificationInfoDB.shareInstance.updateData(info)
            NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateFriendList), object: nil)
//            let requestParam: [String : Any] = ["eventType": 1, "userName": user?.username ?? ""]
            
//            UserCenterApiTool.notify(provider: userProvider, requestParam: requestParam, complete: { (model) in
//                if model?.code == 200 {
            if let u = user {
                NotificationCenter.default.post(name: GlobalNotificationName.didBecomeFriend.name, object: nil, userInfo: ["userName" : u.username])
            }
//                }
//            }) { (error) in
//
//            }
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateConversation), object: nil, userInfo: nil)
        case JMSGFriendEventType.eventNotificationDeclinedFriendInvitation.rawValue:
            info.state = JCVerificationType.reject.rawValue
            JCVerificationInfoDB.shareInstance.updateData(info)
        default:
            break
        }
        if UserDefaults.standard.object(forKey: kUnreadInvitationCount) != nil {
            let count = UserDefaults.standard.object(forKey: kUnreadInvitationCount) as! Int
            UserDefaults.standard.set(count + 1, forKey: kUnreadInvitationCount)
        } else {
            UserDefaults.standard.set(1, forKey: kUnreadInvitationCount)
        }
        NotificationCenter.default.post(name: Notification.Name(rawValue: kUpdateVerification), object: nil)
    }
    
    func _logout() {
        JCVerificationInfoDB.shareInstance.queue = nil
        UserDefaults.standard.removeObject(forKey: kCurrentUserName)
        let c = UIAlertController(title: "您的账号在其它设备上登录", message: nil, preferredStyle: .alert)
        let a1 = UIAlertAction(title: "重新登录", style: .default) { (action) in
            
        }
        let cancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        c.addAction(a1)
        c.addAction(cancel)
        UIApplication.mt_keyWindow?.rootViewController?.present(c, animated: true, completion: nil)
        UserCenter.default.logout()
    }
    
    func onReceive(_ message: JMSGMessage!, error: Error!) {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: kUpdateConversation), object: nil, userInfo: nil)
        _getConversations()
        
    }
    
    @objc func _getConversations() {
        JMSGConversation.allConversations { (result, error) in
            guard let conversatios = result else {
                return
            }
            
            let count = (conversatios as! [JMSGConversation]).unreadCount
            
            let countMinu = (conversatios as! [JMSGConversation]).notFfriendUnreadCount
            
            if let nav = (UIApplication.mt_keyWindow?.rootViewController as? BaseTabBarViewController)?.viewControllers?[1] as? BaseNavController {
                if count - countMinu > 99 {
                    nav.tabBarItem.badgeValue = "99+"
                } else {
                    nav.tabBarItem.badgeValue = count - countMinu == 0 ? nil : "\(count - countMinu)"
                }
            }
        }
    }
}
